<template>
  <CommonPage show-footer title="用户">
    <template #action>
      <div>
        <n-button type="primary" secondary @click="$table?.handleExport()">
          <TheIcon icon="mdi:download" :size="18" class="mr-5" />
          导出
        </n-button>
        <n-button type="primary" class="ml-16" @click="handleAdd">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新建用户
        </n-button>
      </div>
    </template>

    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="extraParams"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.getDiseases"
      @on-checked="onChecked"
      @on-data-change="(data) => (tableData = data)"
    >
      <template #queryBar>
        <QueryBarItem label="用户昵称" :label-width="65">
          <n-input
            v-model:value="queryItems.query"
            type="text"
            placeholder="请输入用户昵称"
            @keypress.enter="$table?.handleSearch"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
    <!-- 新增/编辑/查看 -->
    <CrudModal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :loading="modalLoading"
      :show-footer="modalAction !== 'view'"
      @on-save="handleSave"
    >
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="用户昵称"
          path="nickname"
          :rule="{
            required: true,
            message: '请输入用户昵称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.nickname" placeholder="请输入用户昵称" />
        </n-form-item>
        <n-form-item label="用户头像" path="icon">
          <n-upload
            ref="uploadRef"
            list-type="image-card"
            action=""
            :custom-request="Upload"
            :max="1"
          >
            <img :src="modalForm.avatar_url" style="width: 100%" />
          </n-upload>
        </n-form-item>
      </n-form>
    </CrudModal>

    <!-- 查看就诊卡 -->
    <!-- <CrudModal
      v-model:visible="cardVisible"
      :show-footer="cardAction === 'view'"
      @on-save="handCardleSave"
    >
    <Card></Card>
    </CrudModal> -->
    <n-modal v-model:show="cardVisible">
      <n-card style="width: 800px" size="huge" role="dialog" aria-modal="true">
        <Card :user-id="userForm.id"></Card>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { NButton, NSwitch } from 'naive-ui'
import { formatDateTime, renderIcon, isNullOrUndef } from '@/utils'
import { useCRUD } from '@/composables'
import api from './api'
import baseApi from '@/api'
import Card from '../card/index.vue'

defineOptions({ name: 'Disease' })

const $table = ref(null)
/** 表格数据，触发搜索的时候会更新这个值 */
const tableData = ref([])
/** QueryBar筛选参数（可选） */
const queryItems = ref({})
/** 补充参数（可选） */
const extraParams = ref({})

// 就诊卡管理
const cardVisible = ref(false)
const cardAction = ref('')
const cardTitle = '就诊卡管理'
const cardLoading = ref(false)
const cardFormRef = ref(null)
const userForm = ref({})

onActivated(() => {
  $table.value?.handleSearch()
})

const columns = [
  { title: 'id', key: 'id', width: 50, ellipsis: { tooltip: true } },
  { title: '用户昵称', key: 'nickname', width: 200, ellipsis: { tooltip: true } },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    align: 'center',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleCardView(row),
          },
          {
            default: () => '就诊卡管理',
            icon: renderIcon('material-symbols-light:credit-card', { size: 14 }),
          }
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            style: 'margin-left: 15px;',
            onClick: () => handleView(row),
          },
          { default: () => '查看', icon: renderIcon('majesticons:eye-line', { size: 14 }) }
        ),
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 15px;',
            onClick: () => handleEdit(row),
          },
          { default: () => '编辑', icon: renderIcon('material-symbols:edit-outline', { size: 14 }) }
        ),
      ]
    },
  },
]

// 选中事件
function onChecked(rowKeys) {
  if (rowKeys.length) $message.info(`选中${rowKeys.join(' ')}`)
}

// 发布
function handlePublish(row) {
  if (isNullOrUndef(row.id)) return

  row.publishing = true
  setTimeout(() => {
    row.isPublish = !row.isPublish
    row.publishing = false
    $message?.success(row.isPublish ? '已发布' : '已取消发布')
  }, 1000)
}
const Upload = ({ file, data, headers, withCredentials, action, onFinish }) => {
  let formdata = new FormData() //formdata格式
  formdata.append('image', file.file)
  formdata.append('business', 'image')
  // 接口请求
  baseApi
    .uploadImage(formdata)
    .then((res) => {
      console.log(res)
      modalForm.value.avatar_url = res.data.url
      // 注意清空，要不接口会重复调用
      onFinish()
    })
    .catch((err) => {
      console.log(err)
    })
}

function handleCardView(row) {
  cardAction.value = 'card'
  cardVisible.value = true
  userForm.value = { ...row }
}
function handCardleSave() {
  if (!['card'].includes(cardAction.value)) {
    cardVisible.value = false
    return
  }
  modalFormRef.value?.validate(async (err) => {
    if (err) return
    const actions = {
      add: {
        api: () => doCreate(modalForm.value),
        cb: () => $message.success('新增成功'),
      },
      edit: {
        api: () => doUpdate(modalForm.value),
        cb: () => $message.success('编辑成功'),
      },
    }
    const action = actions[modalAction.value]

    try {
      modalLoading.value = true
      const data = await action.api()
      action.cb()
      modalLoading.value = modalVisible.value = false
      data && refresh(data)
    } catch (error) {
      modalLoading.value = false
    }
  })
}

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '用户',
  initForm: { author: '大脸怪' },
  doCreate: api.addPost,
  doDelete: api.deleteUser,
  doUpdate: api.updateUser,
  refresh: () => $table.value?.handleSearch(),
})
</script>
